/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.restaurant.entity.CommodityRecordRelation;
import org.springblade.modules.restaurant.entity.CommoditySummary;
import org.springblade.modules.restaurant.enums.CommodityArrivalEnums;
import org.springblade.modules.restaurant.enums.CommodityRecordStatusEnums;
import org.springblade.modules.restaurant.excel.CommoditySummaryExcel;
import org.springblade.modules.restaurant.mapper.CommoditySummaryMapper;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommoditySummaryService;
import org.springblade.modules.restaurant.vo.CommoditySummaryVO;
import org.springblade.modules.system.service.ITenantService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 货物采购汇总表 服务实现类
 *
 * @author Blade
 * @since 2025-02-05
 */
@Service
@AllArgsConstructor
public class CommoditySummaryServiceImpl extends BaseServiceImpl<CommoditySummaryMapper, CommoditySummary> implements ICommoditySummaryService {

	private final ICommodityRecordRelationService commodityRecordRelationService;
	private ITenantService tenantService;

	@Override
	public IPage<CommoditySummaryVO> selectCommoditySummaryPage(IPage<CommoditySummaryVO> page, CommoditySummaryVO commoditySummary) {
		return page.setRecords(baseMapper.selectCommoditySummaryPage(page, commoditySummary));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void genCommoditySummary(DateTime startTime, DateTime endTime) {
		try {
			List<String> tenantIds = tenantService.getAllTenantIds();
			for (String tenantId : tenantIds) {
				List<CommodityRecordRelation> commodityRecordRelationList = commodityRecordRelationService.list(Wrappers.<CommodityRecordRelation>lambdaQuery()
					.between(CommodityRecordRelation::getCreateTime, startTime, endTime)
					.eq(BaseEntity::getStatus, CommodityRecordStatusEnums.AUDITED.getStatus())
					.isNotNull(CommodityRecordRelation::getCommodityId)
					.eq(CommodityRecordRelation::getTenantId, tenantId)
				);

				if (commodityRecordRelationList.isEmpty()) {
					log.error("商品采购记录关系表数据为空");
					// 跳出当前循环
					continue;
				}

				// 根据商品ID 求和 组成新的对象
				List<CommodityRecordRelation> commodityRecordRelations = new ArrayList<>(commodityRecordRelationList.stream()
					.collect(Collectors.groupingBy(CommodityRecordRelation::getCommodityId)).entrySet().stream().map(entry -> {
						CommodityRecordRelation commodityRecordRelation = new CommodityRecordRelation();
						BeanUtil.copyProperties(entry.getValue().get(0), commodityRecordRelation);
						commodityRecordRelation.setCommodityId(entry.getKey());
						commodityRecordRelation.setNumber(entry.getValue().stream().mapToInt(CommodityRecordRelation::getNumber).sum());
						return commodityRecordRelation;
					}).toList());

				if (commodityRecordRelations.isEmpty()) {
					log.error("商品采购记录关系表数据为空");
					continue;
				}

				// commodityRecordRelations 根据 sort 排序  会存在分类为空的
				commodityRecordRelations.sort((o1, o2) -> {
					if (o1.getSort() == null) {
						return 1;
					}
					if (o2.getSort() == null) {
						return -1;
					}
					return o1.getSort() - o2.getSort();
				});

				String purchaseTime = DateUtil.formatDate(startTime);
				String arrivalDate = DateUtil.formatDate(DateUtil.offsetDay(startTime, 1));
				List<CommoditySummary> commoditySummaryList =
					commodityRecordRelations.stream().map(commodityRecordRelation -> {
						CommoditySummary item = new CommoditySummary();
						item.setPurchaseTime(purchaseTime);
						item.setArrivalDate(arrivalDate);
						item.setCategoryId(commodityRecordRelation.getCategoryId());
						item.setCategoryName(commodityRecordRelation.getCategoryName());
						item.setSort(commodityRecordRelation.getSort());
						item.setCommodityId(commodityRecordRelation.getCommodityId());
						item.setCommodityName(commodityRecordRelation.getCommodityName());
						item.setNumber(commodityRecordRelation.getNumber());
						item.setActualNumber(BigDecimal.ZERO);
						item.setDifference(item.getActualNumber().subtract(BigDecimal.valueOf(item.getNumber())));
						item.setUnit(commodityRecordRelation.getUnit());
						item.setProductPicture(commodityRecordRelation.getProductPicture());
						item.setStatus(CommodityArrivalEnums.NOT_ARRIVAL.getCode());

						item.setTenantId(tenantId);
						return item;
					}).collect(Collectors.toList());

				if (commoditySummaryList.isEmpty()) {
					log.error("商品采购汇总表数据为空");
					continue;
				}

				// 保存商品采购汇总表
				saveBatch(commoditySummaryList);
			}
		} catch (Exception e) {
			log.error("商品采购汇总表生成异常:", e);
		}
	}

	@Override
	public BigDecimal getCommoditySummaryMonthSum(String businessTime, String tenantId) {
		String startTime = DateUtil.formatDate(DateUtil.beginOfMonth(DateUtil.parse(businessTime)));
		String endTime = DateUtil.formatDate(DateUtil.endOfMonth(DateUtil.parse(businessTime)));
		List<CommoditySummary> commoditySummaryList = list(Wrappers.<CommoditySummary>lambdaQuery()
			.ge(CommoditySummary::getArrivalDate, startTime)
			.le(CommoditySummary::getArrivalDate, endTime)
			.eq(CommoditySummary::getTenantId, tenantId)
		);

		BigDecimal sum = BigDecimal.ZERO;
		for (CommoditySummary commoditySummary : commoditySummaryList) {
			sum = sum.add(commoditySummary.getAmount());
		}
		return sum;
	}

	@Override
	public BigDecimal getCommoditySummaryDaySum(String day, String tenantId) {
		List<CommoditySummary> commoditySummaryList = list(Wrappers.<CommoditySummary>lambdaQuery()
			.eq(CommoditySummary::getArrivalDate, day)
			.eq(CommoditySummary::getTenantId, tenantId)
		);
		BigDecimal sum = BigDecimal.ZERO;
		for (CommoditySummary commoditySummary : commoditySummaryList) {
			sum = sum.add(commoditySummary.getAmount());
		}
		return sum;
	}

	@Override
	public List<CommoditySummaryExcel> exportSummary(List<CommoditySummary> commoditySummaryList) {
		try {
			if (commoditySummaryList.isEmpty()) {
				log.error("商品采购汇总表数据为空");
				return new ArrayList<>();
			}
			// 根据商品ID 求和 组成新的对象
			List<CommoditySummary> commodityRecordRelations = new ArrayList<>(commoditySummaryList.stream()
				.collect(Collectors.groupingBy(CommoditySummary::getCommodityId)).entrySet().stream().map(entry -> {
					CommoditySummary commodityRecordRelation = new CommoditySummary();
					BeanUtil.copyProperties(entry.getValue().get(0), commodityRecordRelation);
					commodityRecordRelation.setCommodityId(entry.getKey());
					commodityRecordRelation.setNumber(entry.getValue().stream().mapToInt(CommoditySummary::getNumber).sum());
					commodityRecordRelation.setAmount(entry.getValue().stream().map(CommoditySummary::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
					commodityRecordRelation.setActualNumber(entry.getValue().stream().map(CommoditySummary::getActualNumber).reduce(BigDecimal.ZERO, BigDecimal::add));
					return commodityRecordRelation;
				}).toList());

			if (commodityRecordRelations.isEmpty()) {
				log.error("商品采购记录关系表数据为空");
				return new ArrayList<>();
			}
			//  根据 sort 排序  会存在分类为空的
			commodityRecordRelations.sort((o1, o2) -> {
				if (o1.getSort() == null) {
					return 1;
				}
				if (o2.getSort() == null) {
					return -1;
				}
				return o1.getSort() - o2.getSort();
			});
			// 转换成excel导出对象
			return commodityRecordRelations.stream().map(commodityRecordRelation -> {
				CommoditySummaryExcel item = new CommoditySummaryExcel();
				item.setCategoryName(commodityRecordRelation.getCategoryName());
				item.setCommodityName(commodityRecordRelation.getCommodityName());
				item.setNumber(commodityRecordRelation.getNumber());
				item.setUnit(commodityRecordRelation.getUnit());
				item.setAmount(commodityRecordRelation.getAmount());
				item.setActualNumber(commodityRecordRelation.getActualNumber());
				item.setDifference(commodityRecordRelation.getActualNumber().subtract(BigDecimal.valueOf(commodityRecordRelation.getNumber())));
				return item;
			}).collect(Collectors.toList());
		} catch (Exception e) {
			log.error("导出异常:", e);
			return new ArrayList<>();
		}
	}
}
